<template>
    <div class="category-list-container p-6">
        <!-- 搜索区域 -->
        <el-card class="mb-4" shadow="never">
            <el-form :model="searchForm" :inline="true" class="search-form">
                <el-form-item label="分类名称">
                    <el-input 
                        v-model="searchForm.name" 
                        placeholder="请输入分类名称" 
                        clearable
                        style="width: 200px"
                        @clear="handleSearch"
                    />
                </el-form-item>
                <el-form-item label="创建日期">
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD"
                        style="width: 280px"
                        @clear="handleSearch"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button :icon="Refresh" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card shadow="never">
            <div class="mb-4">
                <el-button type="primary" :icon="Plus" @click="handleAdd">添加分类</el-button>
            </div>

            <!-- 数据表格 -->
            <el-table 
                :data="tableData" 
                border 
                stripe
                v-loading="loading"
                style="width: 100%"
            >
                <!-- <el-table-column prop="id" label="ID" width="80" align="center" /> -->
                <el-table-column prop="categoryName" label="分类名称" width="300" />
                <el-table-column prop="createTime" label="创建时间" width="200" align="center" />
                <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button 
                            type="primary" 
                            size="small" 
                            :icon="Edit"
                            @click="handleEdit(row)"
                            link
                        >
                            编辑
                        </el-button>
                        <el-button 
                            type="danger" 
                            size="small" 
                            :icon="Delete"
                            @click="handleDelete(row)"
                            link
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="pagination-container mt-4 flex justify-end">
                <el-pagination
                    v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size"
                    :page-sizes="[5, 10, 20, 50, 100]"
                    :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="500px"
            :close-on-click-modal="false"
        >
            <el-form 
                ref="formRef"
                :model="form" 
                :rules="formRules" 
                label-width="100px"
            >
                <el-form-item label="分类名称" prop="categoryName">
                    <el-input 
                        v-model="form.categoryName" 
                        placeholder="请输入分类名称"
                        clearable
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { 
    getCategoryList, 
    addCategory, 
    updateCategory, 
    deleteCategory 
} from '@/api/category'

// 搜索表单
const searchForm = reactive({
    name: '',
    startDate: '',
    endDate: ''
})

// 日期范围
const dateRange = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页数据
const pagination = reactive({
    current: 1,
    size: 5,
    total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加分类')
const formRef = ref(null)
const submitLoading = ref(false)

// 表单数据
const form = reactive({
    id: null,
    categoryName: ''
})

// 表单验证规则
const formRules = {
    categoryName: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ]
}

// 获取分类列表
const getList = async () => {
    loading.value = true
    try {
        const params = {
            current: pagination.current,
            size: pagination.size,
            name: searchForm.name,
            startDate: searchForm.startDate,
            endDate: searchForm.endDate
        }
        
        const res = await getCategoryList(params)
        tableData.value = res.data || []
        pagination.total = res.total || 0
        pagination.current = res.current || 1
        pagination.size = res.size || 5
    } catch (error) {
        ElMessage.error(error || '获取分类列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
        searchForm.startDate = dateRange.value[0]
        searchForm.endDate = dateRange.value[1]
    } else {
        searchForm.startDate = ''
        searchForm.endDate = ''
    }
    
    pagination.current = 1
    getList()
}

// 重置
const handleReset = () => {
    searchForm.name = ''
    searchForm.startDate = ''
    searchForm.endDate = ''
    dateRange.value = []
    pagination.current = 1
    getList()
}

// 每页显示条数变化
const handleSizeChange = (val) => {
    pagination.size = val
    pagination.current = 1
    getList()
}

// 当前页变化
const handleCurrentChange = (val) => {
    pagination.current = val
    getList()
}

// 添加分类
const handleAdd = () => {
    dialogTitle.value = '添加分类'
    form.id = null
    form.categoryName = ''
    dialogVisible.value = true
    
    // 清除表单验证
    if (formRef.value) {
        formRef.value.clearValidate()
    }
}

// 编辑分类
const handleEdit = (row) => {
    dialogTitle.value = '编辑分类'
    form.id = row.id
    form.categoryName = row.categoryName
    dialogVisible.value = true
    
    // 清除表单验证
    if (formRef.value) {
        formRef.value.clearValidate()
    }
}

// 删除分类
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除分类"${row.categoryName}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            await deleteCategory(row.id)
            ElMessage.success('删除成功')
            
            // 如果当前页只有一条数据且不是第一页，则返回上一页
            if (tableData.value.length === 1 && pagination.current > 1) {
                pagination.current--
            }
            
            getList()
        } catch (error) {
            ElMessage.error(error || '删除失败')
        }
    }).catch(() => {
        // 取消删除
    })
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
        if (!valid) return
        
        submitLoading.value = true
        try {
            if (form.id) {
                // 编辑
                await updateCategory({
                    id: form.id,
                    categoryName: form.categoryName
                })
                ElMessage.success('编辑成功')
            } else {
                // 添加
                await addCategory({
                    name: form.categoryName
                })
                ElMessage.success('添加成功')
            }
            
            dialogVisible.value = false
            getList()
        } catch (error) {
            ElMessage.error(error || '操作失败')
        } finally {
            submitLoading.value = false
        }
    })
}

// 页面加载时获取数据
onMounted(() => {
    getList()
})
</script>

<style scoped>
.category-list-container {
    background-color: #f5f7fa;
    min-height: 100vh;
}

.search-form :deep(.el-form-item) {
    margin-bottom: 0;
}

.pagination-container {
    margin-top: 20px;
}
</style>
